package com.san.app.service.impl;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections4.map.CaseInsensitiveMap;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.san.app.dao.InspectDao;
import com.san.app.dao.InspectManager;
import com.san.app.dao.InspectTemplateDao;
import com.san.app.domain.InspectDO;
import com.san.app.domain.InspectHisDTO;
import com.san.app.domain.InspectTemplateDTO;
import com.san.app.service.InspectResultService;
import com.san.app.service.InspectService;
import com.san.app.task.InspectThread;
import com.san.app.vo.InspectHisAllVo;
import com.san.app.vo.InspectHisCheckedVo;
import com.san.app.vo.InspectHisVo;
import com.san.app.vo.InspectResultVO;
import com.san.app.vo.InspectVO;
import com.san.common.utils.AESUtils;
import com.san.common.utils.Constant;
import com.san.common.utils.ExportExcelUtil;
import com.san.metadata.dao.ManageMetadataDao;
import com.san.metadata.domain.BaseLegalPersonDO;
import com.san.metadata.domain.BaseNaturalPersonDO;
import com.san.metadata.domain.ColumnDTO;
import com.san.metadata.domain.DataSourceDO;
import com.san.metadata.service.BaseLegalPersonService;
import com.san.metadata.service.BaseNaturalPersonService;
import com.san.metadata.service.DataSourceService;
import com.san.oa.service.NotifyService;
import com.san.oa.vo.NotifyVO;
/**
 * 审核模板Service实现类
 * @author SuperSR
 * @date 2019年3月26日 上午10:25:00
 *
 */
@Service
public class InspectServiceImpl implements InspectService{

	@Autowired
	private InspectDao dao;
	@Autowired
	private InspectTemplateDao inspectTemplateDao;
	@Autowired
	private ManageMetadataDao manageMetadataDao; 
	@Autowired
	private DataSourceService dataSourceService;
	@Autowired
	private InspectManager inspectManager;
	@Autowired
	private BaseLegalPersonService baseLegalPersonService;
	@Autowired
	private BaseNaturalPersonService baseNaturalPersonService;
	@Autowired
	private InspectResultService inspectResultService;
	@Autowired
	private NotifyService notifyService;
	@Value("${san.uploadPath}")
    private String uploadPath;
	
	//HttpServletResponse  response;
	
	@Override
	public List<InspectDO> list(Map<String, Object> map) {
		return dao.list(map);
	}

	@Override
	public int count(Map<String, Object> map) {
		return dao.count(map);
	}

	@Override
	public int save(InspectVO inspectVO) {
		return dao.save(inspectVO);
	}

	@Override
	public int doEdit(InspectVO inspectVO) {
		return dao.doEdit(inspectVO);
	}

	@Override
	public int remove(Long id) {
		Map<String, Object> map = new HashMap<>();
		map.put("inspectId", id);
		List<InspectTemplateDTO> list = inspectTemplateDao.getTemplateList(map);
		if(list != null && list.size() > 0){
			return -1;
		}else{
			return dao.remove(id);
		}
	}

	@Override
	public int batchRemove(Long[] ids) {
		return dao.batchRemove(ids);
	}

	@Override
	public InspectDO getById(Long inspectId) {
		return dao.getById(inspectId);
	}

	@Override
	public List<Object> doCheck(List<List<String>> datas,Long inspectId,Long batchNo) {
		List<Object> allResult = new ArrayList<>();
		try{
			InspectDO inspectDO = getById(inspectId);
			
			int inspectType = inspectDO.getInspectType();
			Map<String, Object> map = new HashMap<>();
			map.put("inspectId", inspectDO.getInspectId());
			List<InspectTemplateDTO> list =  inspectTemplateDao.getTemplateList(map);
			for (InspectTemplateDTO inspectTemplateDTO : list) {
			
				
				//获取模板中的sql语句
				String templateSql = inspectTemplateDTO.getTemplateSql();
				Long targetSourceId = manageMetadataDao.getById(inspectTemplateDTO.getTableId()).getTargetSourceId();
				//获取数据源DO
				DataSourceDO dataSourceDO = (DataSourceDO) dataSourceService.getById(targetSourceId);
				List<Object> totalList = new ArrayList<>();
				
				if(inspectType == Constant.MANAGE_DATA_TYPE_LEGAL_PERSON){//法人
					for (List<String> data : datas) {
						//历史记录
						InspectHisDTO histDTO=new InspectHisDTO();
						
						histDTO.setBatchNo(batchNo);
						histDTO.setFrmc(data.get(0));
						histDTO.setInspectId(inspectId);
						histDTO.setTyshxydm(data.get(1));
						histDTO.setInspectName(inspectTemplateDTO.getTemplateName());
						List<String> ids = new ArrayList<>();
						List<BaseLegalPersonDO> baseLegalPersonDOs = baseLegalPersonService.getLegalPerson(data.get(0),data.get(1));
						String legalPersonId = "";
						if(baseLegalPersonDOs != null&&baseLegalPersonDOs.size()>0){
							legalPersonId = baseLegalPersonDOs.get(0).getLegalPersonId();
							histDTO.setIsBdcg(1);
						}
						else {
							histDTO.setIsBdcg(0);
						}
						ids.add(legalPersonId);
						@SuppressWarnings("unchecked")
						List<Map<String, Object>> result = inspectManager.getCheckResult(inspectType,data,templateSql, ids.toArray(), dataSourceDO);
						if(result.size()>0) {
							histDTO.setIsValid(1);
						}
						else {
							histDTO.setIsValid(0);
						}
						totalList.add(result);
						inspectResultService.saveHistory(histDTO);
					}
				}else if(inspectType == Constant.MANAGE_DATA_TYPE_NATURAL_PERSON){//自然人
					for (List<String> data : datas) {
						List<String> ids = new ArrayList<>();
						//加密身份证号码
						String idCard = AESUtils.AESEncode(Constant.SECRET_KEY, data.get(1));
						List<BaseNaturalPersonDO> baseNaturalPersonDOs = baseNaturalPersonService.getNaturalPerson(data.get(0), idCard);
						String naturalPersonId = "";
						if(baseNaturalPersonDOs != null){
							naturalPersonId = baseNaturalPersonDOs.get(0).getNaturalPersonId();
						}
						ids.add(naturalPersonId);
						@SuppressWarnings("unchecked")
						List<Map<String, Object>> result = inspectManager.getCheckResult(inspectType,data,templateSql, ids.toArray(), dataSourceDO);
						totalList.add(result);
					}
				}/*else if(inspectType == Constant.MANAGE_DATA_TYPE_LEGAL_PERSON_OR_NATURAL_PERSON){//法人或自然人
					for (List<String> data : datas) {
						List<String> ids = new ArrayList<>();
						List<BaseLegalPersonDO> baseLegalPersonDOs = baseLegalPersonService.getLegalPerson(data.get(0),data.get(1));
						String idCard = "";
						idCard = AESUtils.AESDecode(Constant.SECRET_KEY, data.get(1));
						List<BaseNaturalPersonDO> baseNaturalPersonDOs = baseNaturalPersonService.getNaturalPerson(data.get(0), idCard);
						String legalPersonId = "";
						String naturalPersonId = "";
						if(baseLegalPersonDOs != null){
							legalPersonId = baseLegalPersonDOs.get(0).getLegalPersonId();
						}
						if(baseNaturalPersonDOs != null){
							naturalPersonId = baseNaturalPersonDOs.get(0).getNaturalPersonId();
						}
						ids.add(legalPersonId);
						ids.add(naturalPersonId);
						@SuppressWarnings("unchecked")
						List<Map<String, Object>> result = inspectManager.getCheckResult(inspectType,data,templateSql, ids.toArray(), dataSourceDO);
						totalList.add(result);
					}
				}else if(inspectType == Constant.MANAGE_DATA_TYPE_LEGAL_PERSON_AND_NATURAL_PERSON){//法人和自然人
					for (List<String> data : datas) {
						List<String> ids = new ArrayList<>();
						List<BaseLegalPersonDO> baseLegalPersonDOs = baseLegalPersonService.getLegalPerson(data.get(0),data.get(1));
						String idCard = AESUtils.AESDecode(Constant.SECRET_KEY, data.get(3));
						List<BaseNaturalPersonDO> baseNaturalPersonDOs = baseNaturalPersonService.getNaturalPerson(data.get(2), idCard);
						String legalPersonId = "";
						String naturalPersonId = "";
						if(baseLegalPersonDOs != null && baseLegalPersonDOs.size() > 0){
							legalPersonId = baseLegalPersonDOs.get(0).getLegalPersonId();
						}
						if(baseNaturalPersonDOs != null && baseNaturalPersonDOs.size() > 0){
							naturalPersonId = baseNaturalPersonDOs.get(0).getNaturalPersonId();
						}
						ids.add(legalPersonId);
						ids.add(naturalPersonId);
						@SuppressWarnings("unchecked")
						List<Map<String, Object>> result = inspectManager.getCheckResult(inspectType,data,templateSql, ids.toArray(), dataSourceDO);
						totalList.add(result);
					}
				}else if(inspectType == Constant.MANAGE_DATA_TYPE_NATURAL_PERSON_OR_NATURAL_PERSON){//自然人和自然人
					for (List<String> data : datas) {
						List<String> ids = new ArrayList<>();
						String idCard = AESUtils.AESDecode(Constant.SECRET_KEY, data.get(1));
						List<BaseNaturalPersonDO> baseNaturalPersonDOs = baseNaturalPersonService.getNaturalPerson(data.get(0), idCard);
						String idCard1 = AESUtils.AESDecode(Constant.SECRET_KEY, data.get(3));
						List<BaseNaturalPersonDO> baseNaturalPersonDOs1 = baseNaturalPersonService.getNaturalPerson(data.get(2), idCard1);
						String naturalPersonId = "";
						String naturalPersonId1 = "";
						if(baseNaturalPersonDOs != null){
							naturalPersonId = baseNaturalPersonDOs.get(0).getNaturalPersonId();
						}
						if(baseNaturalPersonDOs1 != null){
							naturalPersonId1 = baseNaturalPersonDOs1.get(0).getNaturalPersonId();
						}
						ids.add(naturalPersonId);
						ids.add(naturalPersonId1);
						@SuppressWarnings("unchecked")
						List<Map<String, Object>> result = inspectManager.getCheckResult(inspectType,data,templateSql, ids.toArray(), dataSourceDO);
						totalList.add(result);
					}
				}*/
				allResult.add(totalList);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return allResult;
	}
	

	@Override
	public void runCheck(InspectService inspectService,List<List<String>> datas, Long inspectId,HttpServletResponse response,Long userId) {
		InspectThread thread = new InspectThread(inspectService,datas, inspectId,response,userId);
		thread.start();
	}
	
	/**
     * 获取response
     **/
    /*private HttpServletResponse getResponse(){
    	ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    	HttpServletResponse response = requestAttributes.getResponse();
		return response;
    }*/

	@SuppressWarnings({ "unchecked","deprecation" })
	@Override
	public void exportExcel(Long inspectId, List<Object> allResult, Date date, Long batchNo,HttpServletResponse response,Long userId) {
		try{
			List<String> tableNameList = new ArrayList<>();
			InspectDO inspectDO = getById(inspectId);
			String inspectName = inspectDO.getInspectName();
			int inspectType = inspectDO.getInspectType();
			Map<String, Object> map = new HashMap<>();
			map.put("inspectId", inspectDO.getInspectId());
			//获取模板列表
			List<InspectTemplateDTO> templateList = inspectTemplateDao.getTemplateList(map);
			for (InspectTemplateDTO template : templateList) {
				Long tableId = template.getTableId();
				String name = manageMetadataDao.getById(tableId).getTargetTableComment();
				tableNameList.add(name);
			}
			HSSFWorkbook workbook = new HSSFWorkbook();		// 创建工作簿对象
			HSSFSheet sheet = workbook.createSheet(inspectName+batchNo);		// 创建工作表
			//sheet样式定义【getColumnTopStyle()/getStyle()均为自定义方法 - 在下面  - 可扩展】
	        HSSFCellStyle columnTopStyle = (HSSFCellStyle)ExportExcelUtil.getColumnTopStyle(workbook);//获取列头样式对象
	        HSSFCellStyle style = (HSSFCellStyle)ExportExcelUtil.getStyle(workbook);					//单元格样式对象
	        FileOutputStream out = null;		//创建输出流
	        int firstRow = 0;	//设置初始行数
			for (int i = 0;i < tableNameList.size();i ++) {
				List<Object> resultList = (List<Object>) allResult.get(i);
				//获取当前操作核查项所需核查字段数组
				String[] columnIds =  inspectTemplateDao.getById(templateList.get(i).getTemplateId()).getColumnId().split(",");
				List<String> columnComments = new ArrayList<>();
				List<String> columnNames = new ArrayList<>();
				for (int j = 0; j < columnIds.length; j++) {
					Long columnId = Long.parseLong(columnIds[j]);
					ColumnDTO columnDTO =  manageMetadataDao.getColumnById(columnId);
					columnNames.add(columnDTO.getColumnName());
					columnComments.add(columnDTO.getColumnComment());
				}
				
				HSSFRow rowm = sheet.createRow(firstRow);
				HSSFCell cellTiltle = rowm.createCell(0);
				//合并单元格
				if(inspectType == Constant.MANAGE_DATA_TYPE_LEGAL_PERSON || inspectType == Constant.MANAGE_DATA_TYPE_NATURAL_PERSON || inspectType == Constant.MANAGE_DATA_TYPE_LEGAL_PERSON_OR_NATURAL_PERSON){
					sheet.addMergedRegion(new CellRangeAddress(firstRow, firstRow + 1, 0, columnIds.length));  
				}else{
					sheet.addMergedRegion(new CellRangeAddress(firstRow, firstRow + 1, 0, columnIds.length + 1));  
				}
				cellTiltle.setCellStyle(columnTopStyle);
				cellTiltle.setCellValue(tableNameList.get(i));
				
				// 定义所需列数
				int columnNum = columnComments.size();
				HSSFRow rowRowName = sheet.createRow(firstRow+2);				// 在索引2的位置创建行(最顶端的行开始的第二行)
				
				// 将列头设置到sheet的单元格中
				if(inspectType == Constant.MANAGE_DATA_TYPE_LEGAL_PERSON){//法人
					for(int n = 0;n < columnNum + 1; n++){
						if(n == 0){
							HSSFCell cellRowName = rowRowName.createCell(0);				//创建列头对应个数的单元格
							cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING);				//设置列头单元格的数据类型
			    			HSSFRichTextString text = new HSSFRichTextString("企业名称");
			    			cellRowName.setCellValue(text);									//设置列头单元格的值
			    			cellRowName.setCellStyle(columnTopStyle);						//设置列头单元格样式
						}else{
							HSSFCell cellRowName = rowRowName.createCell(n);				//创建列头对应个数的单元格
							cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING);				//设置列头单元格的数据类型
			    			HSSFRichTextString text = new HSSFRichTextString(columnComments.get(n-1));
			    			cellRowName.setCellValue(text);									//设置列头单元格的值
			    			cellRowName.setCellStyle(columnTopStyle);						//设置列头单元格样式
						}
					}
				}else if(inspectType == Constant.MANAGE_DATA_TYPE_NATURAL_PERSON){//自然人
					for(int n = 0;n < columnNum + 1; n++){
						if(n == 0){
							HSSFCell cellRowName = rowRowName.createCell(0);				//创建列头对应个数的单元格
							cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING);				//设置列头单元格的数据类型
			    			HSSFRichTextString text = new HSSFRichTextString("自然人名称");
			    			cellRowName.setCellValue(text);									//设置列头单元格的值
			    			cellRowName.setCellStyle(columnTopStyle);						//设置列头单元格样式
						}else{
							HSSFCell cellRowName = rowRowName.createCell(n);				//创建列头对应个数的单元格
							cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING);				//设置列头单元格的数据类型
			    			HSSFRichTextString text = new HSSFRichTextString(columnComments.get(n-1));
			    			cellRowName.setCellValue(text);									//设置列头单元格的值
			    			cellRowName.setCellStyle(columnTopStyle);						//设置列头单元格样式
						}
					}
				}/*else if(inspectType == Constant.MANAGE_DATA_TYPE_LEGAL_PERSON_OR_NATURAL_PERSON){//法人或自然人
					for(int n = 0;n < columnNum + 1; n++){
						if(n == 0){
							HSSFCell cellRowName = rowRowName.createCell(0);				//创建列头对应个数的单元格
							cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING);				//设置列头单元格的数据类型
			    			HSSFRichTextString text = new HSSFRichTextString("企业名称/自然人名称");
			    			cellRowName.setCellValue(text);									//设置列头单元格的值
			    			cellRowName.setCellStyle(columnTopStyle);						//设置列头单元格样式
						}else{
							HSSFCell cellRowName = rowRowName.createCell(n);				//创建列头对应个数的单元格
							cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING);				//设置列头单元格的数据类型
			    			HSSFRichTextString text = new HSSFRichTextString(columnComments.get(n-1));
			    			cellRowName.setCellValue(text);									//设置列头单元格的值
			    			cellRowName.setCellStyle(columnTopStyle);						//设置列头单元格样式
						}
					}
				}else if(inspectType == Constant.MANAGE_DATA_TYPE_LEGAL_PERSON_AND_NATURAL_PERSON){//法人和自然人
					for(int n = 0;n < columnNum + 2; n++){
						if(n == 0){
							HSSFCell cellRowName = rowRowName.createCell(0);				//创建列头对应个数的单元格
							cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING);				//设置列头单元格的数据类型
			    			HSSFRichTextString text = new HSSFRichTextString("企业名称");
			    			cellRowName.setCellValue(text);									//设置列头单元格的值
			    			cellRowName.setCellStyle(columnTopStyle);						//设置列头单元格样式
						}else if(n == 1){
							HSSFCell cellRowName = rowRowName.createCell(1);				//创建列头对应个数的单元格
							cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING);				//设置列头单元格的数据类型
			    			HSSFRichTextString text = new HSSFRichTextString("自然人名称");
			    			cellRowName.setCellValue(text);									//设置列头单元格的值
			    			cellRowName.setCellStyle(columnTopStyle);						//设置列头单元格样式
						}else{
							HSSFCell cellRowName = rowRowName.createCell(n);				//创建列头对应个数的单元格
							cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING);				//设置列头单元格的数据类型
			    			HSSFRichTextString text = new HSSFRichTextString(columnComments.get(n-2));
			    			cellRowName.setCellValue(text);									//设置列头单元格的值
			    			cellRowName.setCellStyle(columnTopStyle);						//设置列头单元格样式
						}
					}
				}else if(inspectType == Constant.MANAGE_DATA_TYPE_NATURAL_PERSON_OR_NATURAL_PERSON){//自然人和自然人
					for(int n = 0;n < columnNum + 2; n++){
						if(n == 0){
							HSSFCell cellRowName = rowRowName.createCell(0);				//创建列头对应个数的单元格
							cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING);				//设置列头单元格的数据类型
			    			HSSFRichTextString text = new HSSFRichTextString("自然人名称1");
			    			cellRowName.setCellValue(text);									//设置列头单元格的值
			    			cellRowName.setCellStyle(columnTopStyle);						//设置列头单元格样式
						}else if(n == 1){
							HSSFCell cellRowName = rowRowName.createCell(1);				//创建列头对应个数的单元格
							cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING);				//设置列头单元格的数据类型
			    			HSSFRichTextString text = new HSSFRichTextString("自然人名称2");
			    			cellRowName.setCellValue(text);									//设置列头单元格的值
			    			cellRowName.setCellStyle(columnTopStyle);						//设置列头单元格样式
						}else{
							HSSFCell cellRowName = rowRowName.createCell(n);				//创建列头对应个数的单元格
							cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING);				//设置列头单元格的数据类型
			    			HSSFRichTextString text = new HSSFRichTextString(columnComments.get(n-2));
			    			cellRowName.setCellValue(text);									//设置列头单元格的值
			    			cellRowName.setCellStyle(columnTopStyle);						//设置列头单元格样式
						}
					}
				}*/
				/*for(int n = 0;n < columnNum; n++){
					HSSFCell cellRowName = rowRowName.createCell(n);				//创建列头对应个数的单元格
					cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING);				//设置列头单元格的数据类型
	    			HSSFRichTextString text = new HSSFRichTextString(columnComments.get(n));
	    			cellRowName.setCellValue(text);									//设置列头单元格的值
	    			cellRowName.setCellStyle(columnTopStyle);						//设置列头单元格样式
	    		}*/
				
				int rowLength = 0;
				//将查询出的数据设置到sheet对应的单元格中
				for(int m = 0;m < resultList.size();m++){
					List<Object> obj = (List<Object>) resultList.get(m);//遍历每个对象
					if(obj != null && obj.size() > 0){
						HSSFRow row = sheet.createRow(firstRow+3+m);//创建所需的行数
						rowLength++;
						for(int a = 0;a < obj.size();a++){
							@SuppressWarnings("rawtypes")
							Map<String, String> nowRow = new CaseInsensitiveMap((Map<String, String>) obj.get(a)) ;
							if(inspectType == Constant.MANAGE_DATA_TYPE_LEGAL_PERSON){//法人
								for(int n = 0; n < columnNames.size() + 1; n++){
									HSSFCell  cell = null;   //设置单元格的数据类型
									cell = row.createCell(n,HSSFCell.CELL_TYPE_STRING);
									String value = "";
									if(n == 0){
										value = nowRow.get("legal_person_name");
									}else{
										value = nowRow.get(columnNames.get(n-1));
									}
									if(!"".equalsIgnoreCase(value) && value != null){
										cell.setCellValue(value);						//设置单元格的值
									}else{
										cell.setCellValue("");
									}
									cell.setCellStyle(style);							//设置单元格样式
								}
							}else if(inspectType == Constant.MANAGE_DATA_TYPE_NATURAL_PERSON){//自然人
								for(int n = 0; n < columnNames.size() + 1; n++){
									HSSFCell  cell = null;   //设置单元格的数据类型
									cell = row.createCell(n,HSSFCell.CELL_TYPE_STRING);
									String value = "";
									if(n == 0){
										value = nowRow.get("natural_person_name");
									}else{
										value = nowRow.get(columnNames.get(n-1));
									}
									if(!"".equalsIgnoreCase(value) && value != null){
										cell.setCellValue(value);						//设置单元格的值
									}else{
										cell.setCellValue("");
									}
									cell.setCellStyle(style);							//设置单元格样式
								}
							}/*else if(inspectType == Constant.MANAGE_DATA_TYPE_LEGAL_PERSON_OR_NATURAL_PERSON){//法人或自然人
								for(int n = 0; n < columnNames.size() + 1; n++){
									HSSFCell  cell = null;   //设置单元格的数据类型
									cell = row.createCell(n,HSSFCell.CELL_TYPE_STRING);
									String value = "";
									if(n == 0){
										value = nowRow.get("legal_or_natural_name");
									}else{
										value = nowRow.get(columnNames.get(n-1));
									}
									if(!"".equalsIgnoreCase(value) && value != null){
										cell.setCellValue(value);						//设置单元格的值
									}else{
										cell.setCellValue("");
									}
									cell.setCellStyle(style);							//设置单元格样式
								}
							}else if(inspectType == Constant.MANAGE_DATA_TYPE_LEGAL_PERSON_AND_NATURAL_PERSON){//法人和自然人
								for(int n = 0; n < columnNames.size() + 2; n++){
									HSSFCell  cell = null;   //设置单元格的数据类型
									cell = row.createCell(n,HSSFCell.CELL_TYPE_STRING);
									String value = "";
									if(n == 0){
										value = nowRow.get("legal_person_name");
									}else if(n == 1){
										value = nowRow.get("natural_person_name");
									}else{
										value = nowRow.get(columnNames.get(n-2));
									}
									if(!"".equalsIgnoreCase(value) && value != null){
										cell.setCellValue(value);						//设置单元格的值
									}else{
										cell.setCellValue("");
									}
									cell.setCellStyle(style);							//设置单元格样式
								}
							}else if(inspectType == Constant.MANAGE_DATA_TYPE_NATURAL_PERSON_OR_NATURAL_PERSON){//自然人和自然人
								for(int n = 0; n < columnNames.size() + 2; n++){
									HSSFCell  cell = null;   //设置单元格的数据类型
									cell = row.createCell(n,HSSFCell.CELL_TYPE_STRING);
									String value = "";
									if(n == 0){
										value = nowRow.get("natural_person_name");
									}else if(n == 1){
										value = nowRow.get("natural_person_name1");
									}else{
										value = nowRow.get(columnNames.get(n-2));
									}
									if(!"".equalsIgnoreCase(value) && value != null){
										cell.setCellValue(value);						//设置单元格的值
									}else{
										cell.setCellValue("");
									}
									cell.setCellStyle(style);							//设置单元格样式
								}
							}*/
						}
					}
				}
				firstRow += 5 + rowLength;
				
				//让列宽随着导出的列长自动适应
				for (int colNum = 0; colNum < columnNum + 2; colNum++) {
		            int columnWidth = sheet.getColumnWidth(colNum) / 256;
		            for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
		                HSSFRow currentRow;
		                //当前行未被使用过
		                if (sheet.getRow(rowNum) == null) {
		                    currentRow = sheet.createRow(rowNum);
		                } else {
		                    currentRow = sheet.getRow(rowNum);
		                }
		                if (currentRow.getCell(colNum) != null) {
		                    HSSFCell currentCell = currentRow.getCell(colNum);
		                    if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
		                        int length = currentCell.getStringCellValue().getBytes().length;
		                        if (columnWidth < length) {
		                            columnWidth = length;
		                        }
		                    }
		                }
		            }
		            if(colNum == 0){
		            	sheet.setColumnWidth(colNum, (columnWidth-2) * 256);
		            }else{
		            	sheet.setColumnWidth(colNum, (columnWidth+4) * 256);
		            }
		        }
			}
			
			if(workbook !=null){
				try
			    {
			        String fileName = inspectName + "-" + batchNo + ".xls";
			        //String headStr = "attachment; filename=\"" + fileName + "\"";
			        //response = getResponse();
			        /*response.setContentType("APPLICATION/OCTET-STREAM");
			        response.setHeader("Content-Disposition", headStr);*/
			        //OutputStream out = response.getOutputStream();
			        out = new FileOutputStream(uploadPath+fileName);  
			        workbook.write(out);
			        //将生成文件信息存入数据库中
			        InspectResultVO inspectResultVO = new InspectResultVO();
					inspectResultVO.setBatchNo(batchNo.toString());
					inspectResultVO.setFilePath(uploadPath+fileName);
					inspectResultVO.setCreateDate(date);
					inspectResultVO.setInspectId(inspectId);
					inspectResultVO.setFileName(fileName);
					inspectResultVO.setSendTo(userId);
					inspectResultVO.setValidCount(allResult.size());
					inspectResultService.save(inspectResultVO);
					
					//向用户发送通知消息
					NotifyVO notify = new NotifyVO();
					notify.setTitle("信用审核模板下载通知");
					notify.setCreateUserId((long) 100000);//系统管理员id
					notify.setContent(inspectName + "核查完成，请前往下载核查结果!");
					notify.setUserIds(new Long[]{userId});
					notify.setCreateDate(date);
					notify.setStatus(Constant.OA_NOTIFY_STATUS_PUBLISH);
					notify.setType(Constant.OA_NOTIFY_TYPE_SYSTEM);
					notify.setRemarks("系统通知");
					notifyService.save(notify);
			    }
			    catch (IOException e)
			    {
			        e.printStackTrace();
			    }finally {
			    	if(out != null){
			    		out.close();
			    	}
					if(workbook != null){
						workbook.close();
					}
				}
			}
			
		} catch (Exception e){
			e.printStackTrace();
		}
		
	}

	@Override
	public int downFile(String fileName,HttpServletResponse res) {
		/*res.setHeader("content-type", "application/octet-stream");
		res.setContentType("application/octet-stream");
		res.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls")*/;
		String headStr = "attachment; filename=\"" + fileName + "\"";
		res.setContentType("APPLICATION/OCTET-STREAM");
        res.setHeader("Content-Disposition", headStr);
		byte[] buff = new byte[1024];
		BufferedInputStream bis = null;
		OutputStream os = null;
		try{
			String filePath =  uploadPath + fileName;
			File file = new File(filePath);
			if(!file.exists()){
				return -1;
			} else {
				os = res.getOutputStream();
				bis = new BufferedInputStream(new FileInputStream(file));
				int i = bis.read(buff);
				while (i != -1) {
					os.write(buff, 0, buff.length);
					os.flush();
					i = bis.read(buff);
				}
			}
		} catch (IOException e){
			e.printStackTrace();
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return 0;
	}

	@Override
	public List<InspectHisVo> hislist(Map<String, Object> map) {
		// TODO Auto-generated method stub
		return dao.hislist(map);
	}

	@Override
	public int hiscount(Map<String, Object> map) {
		// TODO Auto-generated method stub
		return dao.hiscount(map);
	}

	@Override
	public List<InspectHisCheckedVo> historycheckedList(Map<String, Object> map) {
		// TODO Auto-generated method stub
		return dao.historycheckedList(map);
	}

	@Override
	public int historycheckedListCount(Map<String, Object> map) {
		// TODO Auto-generated method stub
		return dao.historycheckedListCount(map);
	}

	@Override
	public List<InspectHisAllVo> historyallList(Map<String, Object> map) {
		// TODO Auto-generated method stub
		return dao.historyallList(map);
	}

	@Override
	public int historyallListCount(Map<String, Object> map) {
		// TODO Auto-generated method stub
		return dao.historyallListCount(map);
	}

}







